package com.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.studay.bean.ChannelPojo;

public class ChannelHandler extends DefaultHandler {

	private Map<String, String> map;
	private ArrayList<ChannelPojo> list;
	private StringBuilder builder;
	private ChannelPojo channelXmlPojo;

	public ChannelHandler() {
		super();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		builder.append(ch, start, length);
		super.characters(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		super.endElement(uri, localName, name);
		// try {
		if (localName.equals("channel")) {
			list.add(channelXmlPojo);
		} else if (localName.equals("xmlurl")) {
			StringTokenizer st = new StringTokenizer(builder.toString(), "\n");
			if (st.hasMoreElements())
				channelXmlPojo.setXmlurl(st.nextToken());
			else
				channelXmlPojo.setXmlurl("");
		} else if (localName.equals("xmlfilename")) {
			StringTokenizer st = new StringTokenizer(builder.toString(), "\n");
			if (st.hasMoreElements())
				channelXmlPojo.setXmlfilename(st.nextToken());
			else
				channelXmlPojo.setXmlfilename("");
		} else if (localName.equals("channelname")) {
			StringTokenizer st = new StringTokenizer(builder.toString(), "\n");
			if (st.hasMoreElements())
				channelXmlPojo.setChannelname(st.nextToken());
			else
				channelXmlPojo.setChannelname("");
		}
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
		builder.setLength(0);
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		list = new ArrayList<ChannelPojo>();
		builder = new StringBuilder();
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, name, attributes);
		map = new HashMap<String, String>();
		// 保存属性
		for (int i = 0; i < attributes.getLength(); i++) {
			map.put(attributes.getQName(i), attributes.getValue(attributes
					.getQName(i)));
		}

		if (localName.equals("channel")) {
			channelXmlPojo = new ChannelPojo();
			channelXmlPojo.setState(map.get("attribute").toString());
			channelXmlPojo.setVersion(map.get("version").toString());
		}
	}

	public ArrayList<ChannelPojo> getList() {
		return list;
	}

	public void setList(ArrayList<ChannelPojo> list) {
		this.list = list;
	}
}